<template>
<el-row>      
          <el-col :xs="24" :sm="24" :lg="24">
    <div class="col-lg-12">
        <div id="reportrange" class="form-control">
            <div class="block">              
                <el-row class="mar-row">
                    <el-col :xs="24" :sm="24" :lg="24">
                        <el-radio-group v-model="radio" class="group-width" @change="changeRadio">
                            <template v-if="isDepart">
                                <el-radio v-show="auth" :label="true" class="marFlex">选择部门:</el-radio>   
                                <el-cascader
                                v-show="auth"
                                v-model="value2"
                                :options="options"
                                :props="props"
                                collapse-tags
                                clearable
                                :disabled="!radio"
                                class="select"
                                @change="handleChange2"></el-cascader>
                            </template>

                            <el-radio :class="{'cancelFlex': !auth, 'cancelFlexDepart': !isDepart}" :label="false" class="mar-l marFlex">选择项目:</el-radio>
                            <el-select :disabled="radio" @change="handleChange" class="select" v-model="val" filterable placeholder="请选择">
                                <el-option
                                v-for="item in options2"
                                :key="item.value"
                                :label="item.label"                                                                 
                                :value="item.label">
                                </el-option>
                                <!-- <el-option value="3903" label="test"></el-option>
                                <el-option value="4352" label="缺陷"></el-option> -->
                            </el-select>                                                              
                        </el-radio-group>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :xs="24" :sm="24" :lg="24">
                        <label v-show="isDate" class="col-form-label mr-1" style="font-size:15px;">时间段：</label>
                        <el-date-picker
                            v-model="dateTime"
                            type="daterange"
                            align="right"
                            size="small"
                            value-format="yyyy-MM-dd"                            
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions" 
                            :default-time="dateTime"
                            v-if="isDate"                         
                            class="mr-4">
                        </el-date-picker>
                        <el-button icon="el-icon-search" type="primary" class="ml-2" @click="search()">搜索</el-button>
                    </el-col>
                </el-row>                                                            
            </div>           
        </div>
        <el-row>
            <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
        </el-row>
    </div>
    </el-col>  
        </el-row>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import { getToken, getName, removeToken, removeName } from '@/utils/auth'
import { getHeader } from '@/app.config'

export default {
    data() {
        return {
            token: getToken(),
            userName: getName(),
            props: { multiple: true },
            val: '',
            value2: [],
            radio: true,
            options: [],                           
            options2: [],
            auth: true,
            user_datetime: Object,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '今年',
                    onClick(picker) {
                    const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
                    const start = new Date(new Date().getFullYear(), 0);
                    start.setTime(start.getTime());
                    picker.$emit('pick', [start, end]);
                    }
                },
                {
                    text: '去年',
                    onClick(picker) {
                    const end = new Date(new Date().getFullYear() - 1, 11, 31);
                    const start = new Date(new Date().getFullYear() - 1, 0);
                    start.setTime(start.getTime());
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            checked: false,
            dateTime: [],
            month: null,
            week: null,
            optionList: [],
            isDate: true,
            isDepart: true         
        }
    },
    computed: {    
        ...mapState({
            filters: state => state.filters,
            allDepartmentList: state => state.allDepartmentList
        }),
        valIndex() {
            let index = ''
            this.options2.forEach((el) => {
                if(el.label == this.val) {
                    index = el.value
                }
            })
            // index = 4352
            return index
        }
    },
    methods: {      
        getTime() {
            let now = new Date()
            let startDate = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())).toISOString().slice(0, 10)
            let endDate = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()+1)).toISOString().slice(0, 10)                      
            this.dateTime.push(startDate)
            this.dateTime.push(endDate)
        },
        changeRadio() {
            if (!this.radio) {
                // this.value2 = []
                if(this.filters.projectName) {
                    this.val = this.filters.projectName
                } else {
                    this.val = this.options2[0].label
                    this.setParams({
                        projectName: this.options2[0].label
                    })
                }               
                this.search()
            } else {
                // this.val = ''
                if(this.filters.departList.length) {
                    this.value2 = this.filters.departList
                } else {
                    this.value2 = this.optionList
                }
                // this.value2 = this.optionList
                //debugger
                this.search()
            }
        },
        formatDateTime(date) {  
            let y = date.getFullYear();  
            let m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;  
            let d = date.getDate();  
            d = d < 10 ? ('0' + d) : d;  
            let h = date.getHours();  
            h=h < 10 ? ('0' + h) : h;  
            let minute = date.getMinutes();  
            minute = minute < 10 ? ('0' + minute) : minute;  
            let second=date.getSeconds();  
            second=second < 10 ? ('0' + second) : second;  
            return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
        },
        toGetTime() {
            // let end = new Date();
            // let start = new Date('2020-12-01');
            // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            // start = this.formatDateTime(start)
            // end = this.formatDateTime(end)
            
            let end = new Date();
            let start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); // 近一个月的时间
            start = this.formatDateTime(start) //格式化日期
            end = this.formatDateTime(end)
            this.dateTime = [start, end] 
        },         
        init() {
            this.toGetTime()
            this.$axios.get(`${process.env.VUE_APP_KANBAN_HOST}/api/account/personal_group_dept`, {headers: getHeader()})
            .then((res) => {                
                if(res.data.code === 200) {
                    this.options2 = res.data.project_info
                    this.options = res.data.dept_info
                    if(!this.options.length) {
                        this.auth = false
                        this.radio = false
                    }
                    this.optionList = this.getArray(this.options)                    
                    let list = this.options
                    let arr = []
                    list.forEach((val) => {
                        val.children.forEach((item) => {
                            arr.push(item.value)
                        })
                    })
                    this.setAll({
                        allDepartmentList: arr
                    })
                } else if(res.data.code == 401) {
                    removeToken()
                    removeName()
                    this.$message.error('登陆超时或该账号已被登出，请您重新登录');
                    this.$router.push({
                        path: '/#/login'
                    })
                } else {
                    console.log('无数据')
                }
            }).catch((err) => {
                console.log(err)
            })
        },
        search: function() {  
            let time, departmentId = '', departList = [], projectName = '', boolRadio, dateTimes = []      
                       
            this.dateTime ? time = this.dateTime.join(',') : time = ''
            
            let timeList = time.split(',')
            if(timeList && timeList[0].length > 10) {
                timeList.forEach((dates, index) => {
                    timeList[index] = dates.split(' ')[0]
                })
                time = timeList.join(',')
            }

            dateTimes = this.dateTime
            
            boolRadio = this.radio

            if(this.value2) {                   
                let arr = []      
                this.value2.forEach((val) => {               
                    val.forEach((item) => {                       
                        if(typeof(item) == 'number') {
                            arr.push(item)
                        }       
                    })
                })    
                departmentId = arr               
                departList = this.value2                
            }           
            let project = this.valIndex
            projectName = this.val
            this.setParams({
                time,
                departmentId,
                departList,
                projectName,
                projectId: project,
                radio: boolRadio,
                dateTimes
            })
            console.log('filterChange')
            this.$emit('filterChange')                 
        },        
        handleChange() {
            this.search()          
        },
        handleChange2() {  
            //console.log(this.value2)
            this.search()                                 
        },
        getArray(array) {
            let outArray = []
            array.forEach((val) => {                         
                val.children.forEach((el) => { 
                    let arr = [val.value, el.value]
                    if(val.value.indexOf(array[0].value) != -1) {                       
                        outArray.push(arr)
                    }                                                                                       
                })
            })            
            return outArray                       
        },
        ...mapMutations([
            'setParams',
            'setAll'
        ])
    },
    created() {      
        if (this.$route.name == 'AvatarUploadDemo' || this.$route.name == 'pipeline') {
            this.isDate = false
        }   
        if(this.filters.dateTimes.length) {
            this.dateTime = this.filters.dateTimes
        } else {
            // this.getTime()
        }        
        this.init()                                   
    },
    mounted() {         
        setTimeout(() => {
            this.radio = this.filters.radio                   
            if(this.filters.projectName) {
                this.val = this.filters.projectName
            } else {
                this.val = this.options2[0].label
            }    
            if(this.filters.departList.length) {
                this.value2 = this.filters.departList
            } else { 
                //console.log(this.optionList)                              
                this.value2 = this.optionList               
            }

            if(this.$route.name == 'buildLoad' || this.$route.name == 'pipeline') {          
                this.isDepart = false           
                this.radio = false
            }
            this.search()
        }, 1000)       
    },
    watch: {        
        // filters: {
        //     handler: function() {
        //         // this.getData()
        //     },
        //     deep: true
        // },
        // radio: function() {
        //     if (!this.radio) {
        //         // this.value2 = []
        //         if(this.filters.projectName) {
        //             this.val = this.filters.projectName
        //         } else {
        //             this.val = this.options2[0].label
        //             this.setParams({
        //                 projectName: this.options2[0].label
        //             })
        //         }               
        //         this.search()
        //     } else {
        //         // this.val = ''
        //         if(this.filters.departList.length) {
        //             this.value2 = this.filters.departList
        //         } else {
        //             this.value2 = this.optionList
        //         }
        //         // this.value2 = this.optionList
        //         //debugger
        //         this.search()
        //     }
        // }     
    }
};
</script>

<style scoped>
    .group-width{
        display: flex;
        flex-wrap: nowrap;
    }
    .marFlex{
        margin: auto;
    }
    .mar-l{
        margin-left: 30px;
    }
    .mar-row{
        margin-bottom: 30px;
    }
    .select{
        width: 40%;
    }
    .border{
        box-sizing: content-box;
        height: 0;
        overflow: visible;
        margin-top: 1rem;
        margin-bottom: 1rem;
        border: 0;
        border-top: 1px solid rgba(0,0,0,.1);
    }
    .form-control {
        background-color: #FFFFFF;
        background-image: none;
        border: 1px solid #e5e6e7;
        border-radius: 1px;
        color: inherit;
        display: block;
        padding: 6px 12px;
        transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
        width: 100%;
        font-size: 0.9rem;
        box-shadow: none;
    }
    label{
        color: rgb(103, 106, 108);
        font-weight: normal;
    }
    .mr-1, .mx-1 {
        margin-right: 1.58rem;
        margin-left: 2.1rem;
        /* padding-left: 2rem; */
    }
    .ml-3, .mx-3 {
        margin-left: 1rem!important;
    }
    .mr-4{
        width: 40%;
    }
    .ml-2{
        float: right;
        margin-right: 4%;
    }
    .col-form-label {
        padding-top: calc(.375rem + 1px);
        padding-bottom: calc(.375rem + 1px);
        margin-bottom: 0;
        font-size: inherit;
        line-height: 1.5;
        font-size: 15px;
    }
    label {
        display: inline-block;
        margin-bottom: .5rem;
    }
    .cancelFlex, .cancelFlexDepart{
        margin: auto 15px;   
    }
</style>